import 'package:flutter/material.dart';
import 'package:flutter_trip/pages/search_page.dart';
import 'package:flutter_trip/plugin/asr_manager.dart';

class SpeakPage extends StatefulWidget {
  @override
  _SpeakPageState createState() => _SpeakPageState();
}

class _SpeakPageState extends State<SpeakPage>
    with SingleTickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController contoller;
  String speakResult ='';
  String speakTips ='长按说话';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    contoller = AnimationController(
        vsync: this, duration: Duration(milliseconds: 1000));
    animation = CurvedAnimation(parent: contoller, curve: Curves.easeIn)
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          contoller.reverse();
        } else if (status == AnimationStatus.dismissed) {
          contoller.forward();
        }
      });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    contoller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
          padding: EdgeInsets.all(30),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _topItem(),
                _bottomItem()
              ],
            ),
          ),

        )
    );
  }
  _topItem(){
    return Column(
      children: [
        Padding(
            padding: EdgeInsets.fromLTRB(0, 30, 0, 30),
          child: Text('你可以这样说',style: TextStyle(fontSize:16,color: Colors.black54 ),),
        ),
        Text('故宫门票\n北京一日游\n天安门',
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 15,color: Colors.grey
          )),
        Padding(
          padding: EdgeInsets.all(20),
          child:Text(speakResult,style: TextStyle(color: Colors.blue),) ,
        )
      ],
    );
  }
  _bottomItem() {
    return FractionallySizedBox(
      widthFactor: 1,
      child: Stack(
        children: [
          GestureDetector(
            onTapDown: (e) {
              _speakStart();
            },
            onTapUp: (e) {
              _speakStop();
            },
            onTapCancel: () {
              _speakCancel();
            },
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    speakTips,
                    style: TextStyle(color: Colors.blue, fontSize: 12),
                  ),
                ),
                Stack(
                  children: [
                    Container(
                      height: MIC_SIZE,
                      width: MIC_SIZE,
                    ),
                    Center(
                      child: AnimatoinMic(animation: animation),
                    ),
                  ],
                )
              ],
            ),
          ),
          Positioned(
              right: 0,
              bottom: 20,
              child: GestureDetector(
                child: Icon(
                  Icons.close,
                  size: 30,
                  color: Colors.grey,
                ),
                onTap: () {
                  print('点击关闭');
                  Navigator.pop(context);
                },
              ))
        ],
      ),
    );
  }

  _speakStart() {
    print('flutter speak start');
    contoller.forward();
    if(speakTips=='长按说话'){
      setState(() {
        speakTips =' - 识别中 - ';
      });
    }
    AsrManager.start(params: {'test':1,'name':'wywinstonwy'}).then((text){
      if(text!=null && text.length>0){
        print('识别结果：$text');
        setState(() {
          speakResult = text;
        });
        Navigator.of(context).pop();
        Navigator.push(context, MaterialPageRoute(builder: (context){
          return SearchPage(false, '', text, '搜索');
        }));
      }else{
        print('未识别到结果');
      }
    }).catchError((e){
      print('==========='+e.toString());
    });
  }

  _speakStop() {
    print('flutter speak stop');
    contoller.reset();
    contoller.stop();
    setState(() {
      speakTips ='长按说话';
    });
    AsrManager.stop();



  }

  _speakCancel() {
    print('flutter speak cancel');
    contoller.reset();
    contoller.stop();
    setState(() {
      speakTips ='长按说话';
    });
    AsrManager.cancel();
  }
}

const double MIC_SIZE = 80;

class AnimatoinMic extends AnimatedWidget {
  static final _opacityTween = Tween(begin: 1, end: 0.5);
  static final _sizeTween = Tween(begin: MIC_SIZE, end: MIC_SIZE - 20);
  final Animation<double> animation;

  const AnimatoinMic({required Animation<double> this.animation})
      : super(listenable: animation);

  @override
  Widget build(BuildContext context) {
    // final Animation<double> animation = listenable;
    // TODO: implement build
    return Opacity(
      opacity: 0.8,
      child: Container(
        height: _sizeTween.evaluate(animation),
        width: _sizeTween.evaluate(animation),
        decoration: BoxDecoration(
          color: Colors.blue,
          borderRadius: BorderRadius.circular(MIC_SIZE / 2),
        ),
        child: const Icon(
          Icons.mic,
          color: Colors.white,
          size: 30,
        ),
      ),
    );
  }
}
